package com.darren.euc.action;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.darren.euc.entity.Function;
import com.darren.euc.entity.User;
import com.darren.euc.service.FunctionService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/function")
public class FunctionAction {
	
	@Autowired
    private FunctionService functionService;
	
	@ResponseBody
    @RequestMapping(value = "/list",method = RequestMethod.POST)
    public JSONArray getFunctionList(HttpServletRequest request,HttpServletResponse response) {
		List<Function> functions = new ArrayList<Function>();
		User user = (User) request.getAttribute("user");
		if(user == null || user.getSuperUser() == 1){
			 functions = functionService.getAll();
		}else if(user != null){
			functions = functionService.getFunctionsByUserId(user.getId());
		}	
    	JSONArray functonArray = constructFunctionTree(functions,0);
        return functonArray;
    }
	
	
	
	
	public static JSONArray constructFunctionTree(List<Function> functions,Integer functionId){
		JSONArray functonArray = new  JSONArray();
		List<Function> children = functions.stream().filter(function -> function.getParentId().equals(functionId)).collect(Collectors.toList()); 
		children.sort((Function function1, Function function2) -> function1.getOrderNumber().compareTo(function2.getOrderNumber()));
		for(Function child: children){
    		JSONObject childJson = JSONObject.fromObject(child);    		
    		childJson.put("children", constructFunctionTree(functions,child.getFunctionId()));
    		functonArray.add(childJson);
    	}
		return functonArray;
	}
	
	
	@ResponseBody
    @RequestMapping(value = "/all",method = RequestMethod.POST)
    public JSONArray getAllFunctions(HttpServletRequest request,HttpServletResponse response) {
    	List<Function> functions = functionService.getAll();    	
    	JSONArray functonArray = constructFunctionTree(functions,0);
        return functonArray;
    }
	
}